<template>
  <el-dialog
      v-model="openDialog"
      :title="dialogTitle"
      :width="1120"
      :before-close="handleClose"
  >
    <div class="new-dialogDiv">
      <!--查询框-->
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px">
        <el-form-item label="版本号" prop="versionCode">
          <el-input style="width:300px" v-model="queryParams.versionCode" placeholder="请输入版本号" clearable />
        </el-form-item>
        <el-form-item label="上传人" prop="uploadUser">
          <el-input  style="width:300px" v-model="queryParams.uploadUser" placeholder="请输入上传人" clearable />
        </el-form-item>
        <el-form-item label="上传日期">
          <el-form-item label-width="0px">
            <el-date-picker style="width:140px" v-model="queryParams.uploadStartTime" type="date" placeholder="开始时间" value-format="YYYY-MM-DD" :disabled-date="startDisabledDate1"/>
          </el-form-item>
          <span class="spanStyle">至</span>
          <el-form-item>
            <el-date-picker style="width:140px"  v-model="queryParams.uploadEndTime" type="date" placeholder="结束时间" value-format="YYYY-MM-DD" :disabled-date="endDisabledDate1"/>
          </el-form-item>
        </el-form-item>
        <!--<el-form-item label="数据范围">
          <el-select v-model="queryParams.dataRangeCountry" placeholder="请选择" @change="chooseScope"
                     style="width:130px;margin-right:10px" clearable>
            <el-option v-for="item in [{ value: 1, label: '国家级' }, { value: 2, label: '省级' }]" :key="item.value"
                       :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-select v-model="queryParams.dataRangeProvince" placeholder="省" style="width:130px;margin-right:10px"
                     @change="chooseProvince" clearable>
            <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="queryParams.dataRangeCity" placeholder="市" style="width:130px;margin-right:10px"
                     @change="chooseCity" clearable>
            <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="queryParams.dataRangeArea" placeholder="区县" style="width:130px;" clearable>
            <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item style="margin-left: 40px;">
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!--版本列表-->
      <el-table v-loading="loading" ref="tableRef" :data="dataList" stripe
                row-key="versionCode">
        <el-table-column type="expand" width="1">
          <template #default="props">
            <div class="expandTable">
              <h3 class="tab-more">更多信息</h3>
              <p><span class="sub-tit">版本说明:</span> {{ props.row.versionDesc }}（此处是版本说明，<span style="color:red">限制300字以内</span> ）</p>
              <p><span class="sub-tit">数据说明:</span> {{ props.row.dataDesc }}（此处是数据说明，<span style="color:red">限制300字以内</span> ）</p>
              <p v-if="props.row.updateDesc"><span class="sub-tit">更新说明:</span> {{ props.row.updateDesc }}</p>
              <p><span class="sub-tit">数据文件:</span>
                <template v-for="item in props.row.dataFileList" v-if="dialogTitle=='坡度数据版本选择' || dialogTitle=='坡向数据版本选择'">
                  <u style="color:#107ce5;cursor: pointer;" @click="handleDownload2(item)">{{ item.attachName }}</u><br />
                </template>
                <template v-for="item in props.row.dataFileList" v-else>
                  <u style="color:#107ce5;cursor: pointer;" @click="handleDownload(item)">{{ item.name }}</u><br />
                </template>
              </p>
              <p><span class="sub-tit">附件:</span>
                <template v-for="item in props.row.attachmentList" v-if="dialogTitle=='坡度数据版本选择' || dialogTitle=='坡向数据版本选择'">
                  <u style="color:#107ce5;cursor: pointer;" @click="handleDownload2(item)">{{ item.attachName }}</u><br />
                </template>
                <template v-for="item in props.row.attachmentList" v-else>
                  <u style="color:#107ce5;cursor: pointer;" @click="handleDownload(item)">{{ item.name }}</u><br />
                </template>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="版本日期" align="center" prop="versionTime" />
        <el-table-column label="版本号" align="center" prop="versionCode" />
        <el-table-column label="数据名称" align="center" prop="dataName" />
        <!--<el-table-column label="数据类别" align="center" prop="dataType" />-->
        <!--<el-table-column label="数据范围" align="center" prop="dataRange" />-->
        <template v-if="dialogTitle=='滑坡现场调查数据版本选择'">
          <el-table-column label="数据范围" align="center" prop="dataRangeStr" />
        </template>
        <template v-else>
          <el-table-column label="数据范围" align="center" prop="dataRange" />
        </template>
        <el-table-column label="上传日期" align="center" prop="uploadTime" />
        <el-table-column label="上传人" align="center" prop="uploadUser" />
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" @click="handleMore(scope.row)">更多数据</el-button>
            <el-button type="text" @click="handleSelect(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
                  @pagination="getList" />
      <!--更多信息-->
      <!--<el-dialog v-model="openMore" width="800px" title="版本信息" append-to-body>
        <el-form ref="moreFormData" :model="currentRow" label-width="120px">
          <p class="mt15"></p>
          <el-form-item label="版本号">{{ currentRow.versionCode }}</el-form-item>
          <el-form-item label="版本日期">{{ currentRow.versionTime }}</el-form-item>
          <el-form-item label="上传日期">{{ currentRow.uploadTime }}</el-form-item>
          <el-form-item label="上传人">{{ currentRow.uploadUserName }}</el-form-item>
          <el-form-item label="数据名称">{{ currentRow.dataName }}</el-form-item>
          &lt;!&ndash;<el-form-item label="数据范围">{{ currentRow.dataRangeStr }}</el-form-item>&ndash;&gt;
          <el-form-item label="版本说明">{{ currentRow.versionDesc }}（此处是版本说明，<span style="color:red">限制300字以内</span> ）</el-form-item>
          <el-form-item label="数据说明">{{ currentRow.dataDesc }}（此处是数据说明，<span style="color:red">限制300字以内</span> ）</el-form-item>
          <el-form-item label="数据文件">
            <template #default="scope">
              <div>
                <p style="margin: 0px;" v-for="item in currentRow.dataFileList">
                  <u style="color:#107ce5;cursor: pointer;" @click="handleDownload2(item)">{{ item.attachName }}</u>
                </p>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="附件">
            <template #default="scope">
              <div>
                <p style="margin: 0px;" v-for="item in currentRow.attachmentList">
                  <u style="color:#107ce5;cursor: pointer;" @click="handleDownload2(item)">{{ item.attachName }}</u>
                </p>
              </div>
            </template>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="openMore=false">关闭</el-button>
          </div>
        </template>
      </el-dialog>-->
    </div>
  </el-dialog>
</template>

<script setup>
// import { getProvince, getChildArea } from "@/api/system/division";
import { getParam1Version,getParam2Version,getParam3Version,getYwVesrionData,queryProvinceNameCodeListByGeomText,getIdByCondition } from "@/api/slideAssess/distributionPatternAnalysis/indexMap";
import { getFileMessage } from "@/api/datamanage/sysData/indexMap.js";

const { proxy } = getCurrentInstance();
const props = defineProps(['open','type','geom']);
const emits = defineEmits(['closeDialog','selectVersionData'])
const loading = ref(false);
const openDialog = ref(false);
const dialogTitle = ref("");
const dataList = ref([]);
const total = ref(0);
// const provinceData = ref([]);//省
// const cityData = ref([]);//市
// const areaData = ref([]); //区、县

//更多信息
const openMore = ref(false);
//当前选中行数据
const currentRow = ref(null);

//是否显示
const isOpen = watch(() => props.open, value => {// watch函数监听props.open
  openDialog.value = value;
},{immediate:true});
//面板标题
const getType = watch(() => props.type, value => {// watch函数监听props.type
  dialogTitle.value = value + "版本选择";
},{immediate:true});

const handleClose = () => {
  openDialog.value = false;
  emits('closeDialog', true);
}

const data = reactive({
  queryParams: {
    typeCode:'',
    versionCode:'',
    uploadUser:'',
    uploadStartTime: '',
    uploadEndTime: '',
    page: 1,
    rows: 10,
    province:'',
    // dataRangeCountry: '',
    // dataRangeProvince: '',
    // dataRangeCity: '',
    // dataRangeArea: '',
  },
})
const { queryParams } = toRefs(data);

const startDisabledDate1 = (time) => {
  if (queryParams.value.uploadEndTime) {
    return time.getTime() > new Date(queryParams.value.uploadEndTime).getTime();
  }
  return false;
};
const endDisabledDate1 = (time) => {
  if (queryParams.value.uploadStartTime) {
    return time.getTime() < new Date(queryParams.value.uploadStartTime).getTime();
  }
  return false;
};

// 监听开始时间和结束时间的变化，更新对应的 disabledDate 函数
watch(queryParams.value.uploadStartTime, (newVal) => {
  // 当开始时间改变时，更新结束时间的选择范围
  endDisabledDate1(newVal);
});

watch(queryParams.value.uploadEndTime, (newVal) => {
  // 当结束时间改变时，更新开始时间的选择范围
  startDisabledDate1(newVal);
});

/** 查询数据列表 */
function getList() {
  loading.value = true;
  let type = props.type;
  if(type=="滑坡现场调查数据"){
    getParam2Version(queryParams.value).then(response => {
      console.log("滑坡现场调查数据");
      console.log(response);
      dataList.value = response.data.rows ? response.data.rows : [];
      total.value = response.data.total;
      loading.value = false;
    }).catch(() => {
      // proxy.$modal.msgError("查询失败");
      loading.value = false;
    });
  }else if(type=="滑坡遥感影像解译数据"){
    getParam3Version(queryParams.value).then(response => {
      console.log("滑坡遥感影像解译数据");
      console.log(response);
      dataList.value = response.data.list ? response.data.list : [];
      total.value = response.data.total;
      loading.value = false;
    }).catch(() => {
      // proxy.$modal.msgError("查询失败");
      loading.value = false;
    });
  }else if(type=="坡度数据" || type=="坡向数据"){
    let dataTypeLevel3 = "dxdmpd";
    if(type=="坡度数据"){
      dataTypeLevel3 = "dxdmpd";
    }else if(type=="坡向数据"){
      dataTypeLevel3 = "dxdmpx";
    }
    let params = {
      dataTypeLevel3 : dataTypeLevel3,//三级数据类别（数据表）id
      versionCode : queryParams.value.versionCode,//版本说明
      uploadUsername:queryParams.value.uploadUser,//上传人用户名
      uploadStartTime: queryParams.value.uploadStartTime,//上传时间开始时间
      uploadEndTime: queryParams.value.uploadEndTime,//上传时间结束时间
      page: queryParams.value.page,
      rows: queryParams.value.rows,
      // distinct:"四川省",//省-市-区县、
      distinct:taskDistrict.value,//省-市-区县、
    }
    //获取业务数据（包括坡度、坡向）版本列表（分页查询）
    getYwVesrionData(params).then((response) => {
      console.log(type);
      console.log(response);
      dataList.value = response.data.rows ? response.data.rows : [];
      total.value = response.data.total;
      loading.value = false;
    }).catch(() => {
      // proxy.$modal.msgError("查询失败");
      loading.value = false;
    });
  }else{
    //获取分布规律分析计算与基础数据关联的数据版本信息
    let tab = getSearchTab(type);
    if(tab){
      getParam1Version(tab,queryParams.value).then(response => {
        console.log("getParam1Version");
        console.log(response);
        dataList.value = response.data.list ? response.data.list : [];
        total.value = response.data.total;
        loading.value = false;
      }).catch(() => {
        // proxy.$modal.msgError("查询失败");
        loading.value = false;
      });
    }
  }
}

//获取查询版本数据的类型tab
function getSearchTab(type){
  // tab :   "1"://断层
  //         "2"://高程
  //         "3"://地层岩性
  //         "4"://道路
  //         "5"://地震动峰值加速度数据（50年超越概率2%）
  //         "6"://地震动峰值加速度数据（50年超越概率10%）
  //         "7"://地震动峰值加速度数据（50年超越概率63%）
  //         "8"://中国地震综合等震线
  let tab = null;
  if(type=="中国地震综合等震线"){
    tab = "8";
  }else if(type=="活断层数据"){
    tab = "1";
  }else if(type=="高程数据"){
    tab = "2";
  }else if(type=="地层岩性数据"){
    tab = "3";
  }

  return tab;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    typeCode:'',
    versionCode:'',
    uploadUser:'',
    uploadStartTime: '',
    uploadEndTime: '',
    page: 1,
    rows: 10,
    province:'',
  };
  dataList.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 更多数据
function handleMore(row) {
  console.log("更多数据");
  console.log(row);
  /*if(dialogTitle.value.indexOf("滑坡现场调查数据")!=-1){
    proxy.$refs['tableRef'].toggleRowExpansion(row);
  }else{
    handleMoreNew(row);//更多数据
  }*/
  proxy.$refs['tableRef'].toggleRowExpansion(row);
}

// 下载文件
function handleDownload(row) {
  var query = {
    attachId: row.id,
    name: row.name
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

// 下载文件
function handleDownload2(row) {
  var query = {
    attachId: row.attachId,
    name: row.attachName
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

/*//获取省列表
function getProvinceData() {
  getProvince().then(response => {
    provinceData.value = response.data;
  });
}

function chooseScope(value) {
  queryParams.value.dataRangeProvince = null;
  queryParams.value.dataRangeCity = null;
  queryParams.value.dataRangeArea = null;
}

function chooseProvince(value) {
  queryParams.value.dataRangeCity = null;
  queryParams.value.dataRangeArea = null;
  cityData.value = [];
  getChildArea(value).then(response => {
    cityData.value = response.data;
  });
}

function chooseCity(value) {
  queryParams.value.dataRangeArea = null;
  areaData.value = [];
  getChildArea(value).then((response) => {
    areaData.value = response.data;
  });
}*/

// 更多信息
const handleMoreNew = (row) =>{
  //当前选中行数据
  currentRow.value = row;
  if(row){
    // proxy.$refs['versionCodeTable'].toggleRowExpansion(row);
    //根据版本号查询文件和附件列表
    getFileMessage(row.versionCode).then((response) => {
      nextTick(() => {
        console.log("根据版本号查询文件和附件列表");
        console.log(response.data);
        let result = response.data;
        if(result){
          currentRow.value.dataFileList = result.dataFileList;//文件
          currentRow.value.attachmentFileList = result.attachmentFileList;//附件
          openMore.value = true;
        }else{
          proxy.$modal.msgWarning("无查询结果");
        }
      });
    });
  }else{
    proxy.$modal.msgWarning("请先勾选1条数据");
  }
}

//选择
function handleSelect(row){
  let attachName = null;
  if(props.type=="高程数据"){
    let dataFileList = row.dataFileList;
    if(dataFileList && dataFileList.length>0){
      for(let i=0;i<dataFileList.length;i++){
        let name = dataFileList[i].name;
        if(name.indexOf(".tif")!=-1){
          attachName = name;
          break;
        }
      }
    }
  }else if(props.type=="坡度数据" || props.type=="坡向数据"){
    let dataFileList = row.dataFileList;
    if(dataFileList && dataFileList.length>0){
      for(let i=0;i<dataFileList.length;i++){
        let name = dataFileList[i].attachName;
        if(name.indexOf(".tif")!=-1){
          attachName = name;
          break;
        }
      }
    }
  }
  let obj = {
    versionCode:row.versionCode,
    type:props.type,
    attachName:attachName
  }
  emits("selectVersionData",obj);
  handleClose();
}

//任务范围：省-市-县、
const taskDistrict = ref("");
//根据地图圈选区域，查询行政区划--省|市|区县的名称和code列表
function queryTaskRegionNameCodeListByGeomText(geomText) {
  loading.value = true;
  // console.log("查询行政区划名称和code列表"+geomText);
  queryProvinceNameCodeListByGeomText(geomText).then((response) => {
    nextTick(() => {
      console.log("查询行政区划名称和code列表result:");
      console.log(response.data);
      let list = response.data;
      if(list && list.length==2 && list[0].length>0){
        let nameList = list[0];//行政区划名称列表
        let province = "";
        let regionArr = [];
        for(let i=0;i<nameList.length;i++){
          let name = nameList[i];//省
          if(name && regionArr.indexOf(name)==-1){
            province = name;//省
            regionArr.push(name);
          }
        }
        if(regionArr.length==1){//任务范围不跨省：可选国家级-全国、任务所在省
          taskDistrict.value = province;
          console.log("任务所在省："+province);
          //根据省市县名称查询id
          getIdByCondition(province,"","").then((response) => {
            console.log(response);
            if(response.data){
              queryParams.value.province = response.data;//ID
              loading.value = false;
              //查询数据
              getList();
            }
          }).catch(() => {
            // proxy.$modal.msgError("查询失败");
            loading.value = false;
          });
        }else{//任务范围跨省的：可选国家级-全国
          taskDistrict.value = "";
          queryParams.value.province = "";
          console.log("国家级-全国");
          loading.value = false;
          //查询数据
          getList();
        }
      }
    });
  });
}

//获取范围空间数据
const getGeom = watch(() => props.geom, value => {// watch函数监听props.geom
  if(value){
    console.log("获取范围空间数据");
    // console.log(value);
    //根据地图圈选区域，查询行政区划--省|市|区县的名称和code列表
    queryTaskRegionNameCodeListByGeomText(value);
  }
},{immediate:true});

onMounted(() => {
  // getProvinceData();
  // getList();
})
</script>

<style scoped lang="scss">
.new-dialogDiv {
  padding:20px;
}

.expandTable {
  padding: 5px 20px 5px 205px;

  h3 {
    font-weight: bold;
  }

  p {
    margin: 0px;
    line-height: 25px !important;
  }
}

.tab-more{
  font-size: 16px;
  font-weight: bold;
  border-left: 3px solid #000000;
  font-family: PingFangSC-Medium;
  padding-left: 10px;
  margin-bottom: 20px;
}
.sub-tit{
  font-size: 14px;
  color: #707070;
  margin-bottom: 20px;
  margin-right: 10px;
  display: inline-block;
  font-weight: 600;
}

:deep(.el-drawer__header) {
  margin-bottom: 0px !important;
}

.el-form--inline .el-form-item{
  margin-right: 0px!important;
}
.spanStyle{
  display: inline-block;
  width: 20px;
  text-align: center;
}
:deep(.el-table__expand-icon){
  display: none;
}
</style>